require.config({
    //Debug mode
    baseUrl: "assets/js", 
    //Release mode
    //baseUrl: "assets/js/min", 
});

require(["jquery", "App"], function($, App){
    $(document).bind("mobileinit", function(){
        $.extend($.mobile, App.jqmConfig || {});
    });
    
    require([
        "jquery.mobile",
        "jquery.mobile.subpage",
        "jquery.mobile.datepicker",
        "Neptuno.Util"
        ], function($){
        
            var self = this;
            //Loaded module names
            self.loadedModules = [];
            //Logs text if application is in debug mode.
            self.log = function(text){
                if(App.debug){
                    console.log(text);
                }
            }
            /**
         * Explicitly loads a module if not already loaded. 
         * @param moduleName The module name to load.
         */
            self.loadModule = function(moduleName){
                var moduleIndex = $.inArray(moduleName, self.loadedModules);
                if(moduleIndex == -1){
                    require([moduleName], function(){
                        self.loadedModules.push(moduleName);
                        self.log(moduleName + " loaded.");
                        $.mobile.activePage.trigger("pagecreate");
                    });
                }
            }
            /**
         * Module registerer function.
         * 
         * @param forPage The page element identifier, can be any jQuery selector.
         * @param moduleName The name of the module.
         */
            self.registerModule = function (forPage, moduleName){
                var page = $(forPage);
                //If the page for the  module is present, then load it, 
                //this is for cases when page gets refreshed.
                if(page.length !== 0){
                    self.loadModule(moduleName);
                }
                page.live('pageinit', function(){
                    self.loadModule(moduleName);
                });        
            }
    
            self.log("Application Start.");
            $.each(App.modules, self.registerModule);
        
            //The menu
            $("#dropdown-menu").live("change", function(){
                var url = $(this).val();
            
                if($.mobile.activePage.attr("data-role") == "dialog"){
                    $.mobile.activePage.one("pagehide", function(){
                        $.mobile.changePage(url);
                    });
                }else{
                    $.mobile.changePage(url);
                }
                return false;
            });
            
            if($.mobile.activePage != null){
                $.mobile.activePage.trigger("pagecreate");
            }
        });
});
